package com.wfm.mianshi.多个线程打印ABCABC.利用线程池;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
    static class PrintTask implements Runnable {
        private final String letter;
        private final Semaphore currentSemaphore;
        private final Semaphore nextSemaphore;
        private static final int PRINT_TIMES = 3;

        public PrintTask(String letter, Semaphore currentSemaphore, Semaphore nextSemaphore) {
            this.letter = letter;
            this.currentSemaphore = currentSemaphore;
            this.nextSemaphore = nextSemaphore;
        }

        @Override
        public void run() {
            for (int i = 0; i < PRINT_TIMES; i++) {
                try {
                    // 获取当前信号量的许可
                    currentSemaphore.acquire();
                    System.out.print(letter);
                    // 释放下一个信号量的许可
                    nextSemaphore.release();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    public static void main(String[] args) {
        // 创建信号量，初始时 A 线程可以执行
        Semaphore semaphoreA = new Semaphore(1);
        Semaphore semaphoreB = new Semaphore(0);
        Semaphore semaphoreC = new Semaphore(0);

        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // 创建打印任务
        PrintTask taskA = new PrintTask("A", semaphoreA, semaphoreB);
        PrintTask taskB = new PrintTask("B", semaphoreB, semaphoreC);
        PrintTask taskC = new PrintTask("C", semaphoreC, semaphoreA);

        // 提交任务到线程池
        executorService.submit(taskA);
        executorService.submit(taskB);
        executorService.submit(taskC);

        // 关闭线程池
        executorService.shutdown();
    }
}
